<template>
  <el-scrollbar ref="scrollRef" @scroll="scroll">
    <div class="x-catalogue-content-wrap" ref="wrapRef">
      <div
        class="u-children"
        data-layer="0"
        v-if="data?.length > 0"
        v-for="firstItem in data"
      >
        <!-- 第一层 -->
        <div class="u-header" :[anchorAttr]="firstItem.index">
          {{ firstItem.title }}
        </div>
        <slot v-if="firstItem.index" :name="firstItem.index"></slot>
        <div
          class="u-children"
          data-layer="1"
          v-if="firstItem?.children?.length > 0"
          v-for="secondItem in firstItem.children"
        >
          <!-- 第二层 -->
          <div class="u-header" :[anchorAttr]="secondItem.index">
            {{ secondItem.title }}
          </div>
          <slot v-if="secondItem.index" :name="secondItem.index"></slot>
          <div
            class="u-children"
            data-layer="2"
            v-if="secondItem?.children?.length > 0"
            v-for="thirdItem in secondItem.children"
          >
            <!-- 第三层 -->
            <div class="u-header" :[anchorAttr]="thirdItem.index">
              {{ thirdItem.title }}
            </div>
            <slot v-if="thirdItem.index" :name="thirdItem.index"></slot>
          </div>
        </div>
      </div>
    </div>
  </el-scrollbar>
</template>

<script setup name="XCataloguContent">
import { ref } from 'vue'

const props = defineProps({
  data: Array, // Array<{ title, index, children }>
  anchorAttr: {
    type: String,
    default: 'data-index',
  },
})

const emit = defineEmits(['scroll'])

const scrollRef = ref()
const wrapRef = ref()

// 正文滚动到具体元素
function scrollTo(anchorId) {
  const contentEl = wrapRef.value.querySelector(
    `[${props.anchorAttr}='${anchorId}']`
  )
  if (contentEl) {
    scrollRef?.value?.setScrollTop(contentEl.offsetTop)
  } else {
    console.error('锚点不存在：' + anchorId)
  }
}

function scroll({ scrollTop }) {
  emit('scroll', scrollTop)
}

defineExpose({
  scrollTo,
  wrapRef,
})
</script>

<style lang="scss" scoped>
.x-catalogue-content-wrap {
  flex: 1;
}
</style>
